package com.situ.personal.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.personal.entity.User;
import com.situ.personal.service.UserService;


@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet{
	private UserService userService = new UserService();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//req.setCharacterEncoding("UTF-8");
		
		String method = req.getParameter("method");
		switch (method) {
		case "login":
			login(req, resp);
			break;
		case "logout":
			logout(req, resp);
			break;
		default:
			break;
		}
	}

	private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		HttpSession session = req.getSession();
		session.invalidate();
		//销毁Session之后重定向到登录界面
		resp.sendRedirect(req.getContextPath() + "/user_login.jsp");
	}

	private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String checkCode = req.getParameter("checkCode");
		// 将用户输入的验证码和后台生成的验证码比较一下
		HttpSession session = req.getSession();
		String checkCodeSession = (String)session.getAttribute("checkCodeSession");
		//if (checkCode == null ||  checkCode.equalsIgnoreCase(checkCodeSession) == false) {
		if (checkCode == null || !checkCode.equalsIgnoreCase(checkCodeSession)) {
			resp.sendRedirect(req.getContextPath() + "/user_login.jsp");
			return;
		}
		
		String name = req.getParameter("name");
		String password = req.getParameter("password");
		
		User user = userService.login(name, password);
		// 如果存在这样一个User对象，这个用户登录成功
		if (user != null) {
			// 将这个用户信息放到Session，判断用户是否登录就是根据Session里面有没有
			// 这个用户信息
			session.setAttribute("user", user);
			// 登录完成之后重定向到学生列表界面
			// resp.sendRedirect(req.getContextPath() + "/user?method=findByPage");
			// /Java1912WebPersonal/
			resp.sendRedirect(req.getContextPath() + "/");
		} else {// 登录失败
			resp.sendRedirect(req.getContextPath() + "/fail.jsp");
		}
	}
}
